package com.aifast.system.sys.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aifast.common.base.R;
import com.aifast.common.global.Const;
import com.aifast.common.layui.LayuiDataTable;
import com.aifast.common.layui.LayuiPageFactory;
import com.aifast.common.util.SideMenu;
import com.aifast.system.sys.dao.SysAuthoritiesDao;
import com.aifast.system.sys.dao.SysRoleAuthorityDao;
import com.aifast.system.sys.entity.SysAuthorities;
import com.aifast.system.sys.entity.SysRole;
import com.aifast.system.sys.entity.SysRoleAuthority;
import com.aifast.system.sys.entity.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author fujian
 * @since 2022-01-07
 */
@Service
@RequiredArgsConstructor
public class SysAuthoritiesService extends ServiceImpl<SysAuthoritiesDao, SysAuthorities> {

    private final SysAuthoritiesDao dao;
    private final SysRoleAuthorityDao sysRoleAuthorityDao;

    /**
     * layui数据表格列表查询方法
     * <br>这里参数不使用参数类，当超过5个参数时筛选条件参数建议使用参数类param封装
     * @param search 关键字搜索
     * @param page   分页
     * @return 列表数据
     */
    public LayuiDataTable list(String search, Page page) {
        LambdaQueryWrapper<SysAuthorities> wrapper = new LambdaQueryWrapper<SysAuthorities>()
                .eq(StrUtil.isNotBlank(search), SysAuthorities::getName, search)
                .orderByDesc(SysAuthorities::getSort);
        return LayuiPageFactory.init(page(page, wrapper));
    }

    /**
     * 新增或者查询
     * <br>vo的方法另写，里面有判定是否新增还是修改 可自定义逻辑
     *
     * @param sysAuthorities
     * @return
     */
    public Boolean insertOrUpdate(SysAuthorities sysAuthorities) {
        if (ObjectUtil.isNotNull(sysAuthorities.getId())) {

            /*if(StrUtil.isNotBlank(sysAuthorities.getAuthority())){
                UserInfo.removeByAuthorities(sysAuthorities.getAuthority());
            }*/
        }
        return saveOrUpdate(sysAuthorities);
    }

    /**
     * 删除方法
     * <br>提供单个删除和批量删除
     *
     * @param id  数据id
     * @param ids 数据id集合
     * @return
     */
    public Boolean del(Integer id, String ids) {
        List<Integer> integers = new ArrayList<>();
        if (StrUtil.isNotBlank(ids)) {
            integers = Convert.toList(Integer.class, ids.split(","));
        }
        if (ObjectUtil.isNotNull(id)) {
            integers.add(id);
        }
        try {
            integers.forEach(i -> {
                update(new UpdateWrapper<SysAuthorities>().set("deleted", 1).eq("id", i));
            });
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 数据详情
     *
     * @param id 数据id
     * @return
     */
    public R info(Integer id) {
        if (ObjectUtil.isNull(id)) return R.ERROR();
        SysAuthorities one = getOne(new QueryWrapper<SysAuthorities>().eq("id", id));
        return R.OK(one);
    }

    public R getAuthTree(Integer roleId) {
        if(ObjectUtil.isNull(roleId)){
            return R.ERROR();
        }
        return R.OK(dao.getAuthTree(roleId));

    }

    @Transactional
    public boolean addRoleAuth(Integer roleId, String authIds) {

        if(ObjectUtil.isNull(roleId) || StrUtil.isBlank(authIds)){
            return false;
        }
        int role_id = sysRoleAuthorityDao.deleteByRoleId(roleId);
        String[] split = authIds.split(Const.SYMBOL_COMMA);
        for (String s : split) {
            SysRoleAuthority build = SysRoleAuthority.builder().roleId(roleId).authorityId(Convert.toInt(s)).build();
            sysRoleAuthorityDao.insert(build);
        }
        return true;

    }

    public List<SideMenu> getSideMenu() {
        List<SysAuthorities> list = new ArrayList<>();
        if (UserInfo.isAdmin()) {
            list = list(new QueryWrapper<SysAuthorities>().in("type", 1, 2).orderByDesc("sort"));
        } else {
            List<SysRole> roles = UserInfo.get().getRoles();
            if (ObjectUtil.isNull(roles) || roles.size() == 0) {
                return null;
            }
            List<Integer> collect = roles.stream().map(SysRole::getId).collect(Collectors.toList());
            List<SysRoleAuthority> authorities = sysRoleAuthorityDao.selectList(new QueryWrapper<SysRoleAuthority>().in("role_id", collect));
            if (ObjectUtil.isNull(authorities) || authorities.size() == 0) {
                return null;
            }
            List<Integer> integers = authorities.stream().map(SysRoleAuthority::getAuthorityId).collect(Collectors.toList());
            list = list(new QueryWrapper<SysAuthorities>().in("id", integers).in("type", 1, 2).orderByDesc("sort"));
        }
        List<SideMenu> res = new ArrayList<>();
        list.forEach(i -> {
            res.add(SideMenu.builder().id(i.getId()).pid(i.getPid()).name(i.getName()).icon(i.getIcon()).url(i.getUrl()).subMenus(new ArrayList<>()).build());
        });
        return SideMenu.init(res);

    }
}
